//
//  KKImagePickerController.m
//  SHDoctor
//
//  Created by Mac mini on 15/10/13.
//  Copyright © 2015年 ShiHeng. All rights reserved.
//

#import "KKImagePickerController.h"
#import "KKAlertView.h"
#import "KKLoadingView.h"
#import "KKPhotoGroupViewController.h"
#import "KKPhotoListViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>

#import <AVFoundation/AVFoundation.h>

@interface KKImageNavigationController : UINavigationController {
    
    NSArray* _leftButtons;
}

- (void)navigationBack:(UIButton*)sender;

@end

@implementation KKImageNavigationController

- (void)loadView {
    [super loadView];
    
//    self.navigationBar.barTintColor = [UIColor colorWithRed:48.0/255.0 green: 128.0/255.0 blue:248.0/255.0 alpha: 1.0];
//    self.toolbar.barTintColor = [UIColor colorWithRed:48.0/255.0 green: 128.0/255.0 blue:248.0/255.0 alpha: 1.0];
    
//    self.navigationBar.barTintColor = [UIColor colorWithHexString: @"#33cccc"];
//    self.toolbar.barTintColor = [UIColor colorWithHexString: @"#33cccc"];
    self.navigationBar.barTintColor = [UIColor whiteColor];
    self.toolbar.barTintColor = [UIColor blackColor];
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:18],NSFontAttributeName, nil];
    self.navigationBar.translucent = NO;
    [self.navigationBar setTitleTextAttributes:attributes];
    
//    UIButton* _backButton = [UIButton buttonWithType: UIButtonTypeCustom];
//    _backButton.frame = CGRectMake(0, 0, 45, 40);
//    _backButton.titleLabel.font = [UIFont systemFontOfSize: 16.0];
//    [_backButton setTitle: @"返回" forState: UIControlStateNormal];
//    [_backButton setTitleEdgeInsets: UIEdgeInsetsMake(0, 5, 0, 0)];
//    [_backButton setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
//    [_backButton setTitleColor: [UIColor lightGrayColor] forState: UIControlStateHighlighted];
//    [_backButton setImage: [UIImage imageNamed: @"kk_item_back"] forState: UIControlStateNormal];
//    [_backButton addTarget: self action: @selector(navigationBack:) forControlEvents: UIControlEventTouchUpInside];
//    
//    {
//        UIBarButtonItem* leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView: _backButton];
//        UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
//        spaceItem.width = -8;
//        
//        _leftButtons = @[spaceItem,leftButtonItem];
//    }
    
    self.navigationItem.hidesBackButton = YES;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [super pushViewController: viewController animated: animated];
    
    if (self.viewControllers.count > 1) {
        [viewController.navigationItem setLeftBarButtonItems: _leftButtons animated: YES];
    }
}

- (UIViewController*)popViewControllerAnimated:(BOOL)animated {
    if (self.viewControllers.count == 2) {
        [self.navigationItem setLeftBarButtonItem: nil animated: YES];
    }
    return [super popViewControllerAnimated: animated];
}

- (void)navigationBack:(UIButton*)sender {
    
    if (self.viewControllers.count > 1) {
        UIViewController* lastViewController = [self.viewControllers lastObject];
        [lastViewController.navigationController popViewControllerAnimated: YES];
    }
}

@end

#pragma mark - KKImagePickerController methods

@interface KKImagePickerController() <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
    
    KKImagePickerModel* _imagePickerModel;
    NSDateFormatter* _dateFormatter;
    ALAssetsLibrary* _assetsLibrary;
    //  相机
    UIImagePickerController* _cameraPickerController;
    
    KKImageNavigationController* _navigationController;
    KKPhotoGroupViewController* _photoGroupViewController;
}

- (void)listenActionMethods:(NSNotification*)notification;

@end

@implementation KKImagePickerController

static KKImagePickerController* imagePickerController = nil;
+ (instancetype)shareImagePickerManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imagePickerController = [[self class] new];
    });
    return imagePickerController;
}

- (id)init {
    self = [super init];
    if (self) {
        
        _assetsLibrary = [ALAssetsLibrary new];
        
        _imagePickerModel = [KKImagePickerModel sharedManager];
        
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat: @"yyyy:MM:dd HH:mm:ss"];
        
        //  相机
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            _cameraPickerController = [UIImagePickerController new];
            _cameraPickerController.delegate = self;
            _cameraPickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        //  相册
        _photoGroupViewController = [KKPhotoGroupViewController new];
        _navigationController = [[KKImageNavigationController alloc] initWithRootViewController: _photoGroupViewController];
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(listenActionMethods:) name: KKImagePickerControllerNotificationActionOfSend object: nil];
    }
    return self;
}

- (void)setMaxCount:(NSInteger)maxCount {
    _maxCount = maxCount;
    
    [[KKImagePickerModel sharedManager] setMaxCount: _maxCount];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

#pragma mark - Public methods

- (void)takePicture {
    
    if (![self kk_authStatusWithCamera]) {
        return;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && _cameraPickerController == nil) {
        _cameraPickerController = [UIImagePickerController new];
        _cameraPickerController.delegate = self;
        _cameraPickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    
    if (_cameraPickerController == nil) {
        
        [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"置暂不支持拍照功能" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
        return;
    }
    
    [_imagePickerModel cleanAllItems];
    
    UIViewController* rootViewController = (UIViewController*)_delegate;
    
    if (![rootViewController isKindOfClass: [UIViewController class]]) {
        UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];
        rootViewController = keyWindow.rootViewController;
    }
    
    [rootViewController presentViewController: _cameraPickerController animated: YES completion: nil];
}

- (void)getPhotosFromAlbum {
    
    if (_navigationController == nil) {
        return;
    }
    
    [_imagePickerModel cleanAllItems];
    
    if (![self kk_authStatusWithAlbum]) {
        return;
    }
    
    
    UIViewController* rootViewController = (UIViewController*)_delegate;
    
    if (![rootViewController isKindOfClass: [UIViewController class]]) {
        UIWindow* keyWindow = [[UIApplication sharedApplication] keyWindow];
        rootViewController = keyWindow.rootViewController;
    }
    
    [rootViewController presentViewController: _navigationController animated: YES completion: nil];
}

//不缩放
+ (UIImage*)fullImageFromAsset:(ALAsset*)asset {
    
    ALAssetRepresentation *assetRep = [asset defaultRepresentation];
    CGImageRef imageRef = [assetRep fullResolutionImage];
    UIImage *image = [UIImage imageWithCGImage: imageRef scale: assetRep.scale orientation: (UIImageOrientation)assetRep.orientation];
    return image;
}
//缩放
+ (UIImage*)thumbImageFromAsset:(ALAsset*)asset {
    
    return [UIImage imageWithCGImage: asset.thumbnail];
}

#pragma mark - Private methods

- (BOOL)kk_authStatusWithCamera {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo];
    
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
        {
            __weak typeof(self) weakSelf = self;
            [AVCaptureDevice requestAccessForMediaType: AVMediaTypeVideo completionHandler:^(BOOL granted) {
                
                if (granted) {
                    [weakSelf takePicture];
                }
            }];
            
            return false;
        }
            break;
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied:
        {
            [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"请在设备的\"设置-隐私-相机\"中允许访问相机权限" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
            return false;
        }
            break;
        default:
            break;
    }
    
    return true;
}

- (BOOL)kk_authStatusWithAlbum {
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        switch (authStatus) {
            case ALAuthorizationStatusRestricted:
            case ALAuthorizationStatusDenied:
            {
                [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
                return false;
            }
                break;
            default:
                break;
        }
    }
    else {
        
        PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
        switch (authStatus) {
            case PHAuthorizationStatusNotDetermined:
            {
                __weak typeof(self) weakSelf = self;
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    
                    if (status == PHAuthorizationStatusAuthorized) {
                        [weakSelf getPhotosFromAlbum];
                    }
                }];
                
                return false;
            }
                break;
            case PHAuthorizationStatusRestricted:
            case PHAuthorizationStatusDenied:
            {
                [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
                return false;
            }
                break;
            default:
                break;
        }
    }
    
    
    return true;
}


- (void)listenActionMethods:(NSNotification*)notification {
    
    if ([notification.name isEqualToString: KKImagePickerControllerNotificationActionOfSend]) {
        
        NSDictionary* info = notification.userInfo;
        
        NSString* type = info[@"type"];
        if ([type isEqualToString: @"save"]) {
            
//            NSMutableArray* imageURLs = [NSMutableArray array];
//            
//            NSInteger count = [[KKImagePickerModel sharedManager] count];
//            
//            for (NSInteger index = 0; index < count; index++) {
//                ALAsset* asset = [[KKImagePickerModel sharedManager] itemOfIndex: index];
//                
//                NSURL* itemURL = [asset valueForProperty: ALAssetPropertyAssetURL];
//                [imageURLs addObject: itemURL];
//            }
            
            if (_delegate && [_delegate respondsToSelector: @selector(imagePickerController:didSelectedPhotos:)]) {
                [_delegate imagePickerController: self didSelectedPhotos: [[KKImagePickerModel sharedManager] allItems]];
            }
        }
        
        __weak typeof(_navigationController) weakNavigationController = _navigationController;
        [_navigationController dismissViewControllerAnimated: true completion: ^{
            [weakNavigationController popToRootViewControllerAnimated: false];
        }];
        
        return;
    }
}

#pragma mark -

- (void)saveImageToAssetsLibraryWithImage:(UIImage*)image {
    
    if (image == nil) {
        return;
    }
    
    __block NSString* blockGroupName = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleName"];
    __block NSMutableArray* groupArray = [NSMutableArray array];
    __block ALAssetsLibrary* blockLibiary = _assetsLibrary;
    __block typeof(self) blockSelf = self;
    //
    ALAssetsLibraryGroupsEnumerationResultsBlock listResultsBlock = ^(ALAssetsGroup* group, BOOL *stop) {
        if (group) {
            [groupArray addObject: group];
        }
        else {
            
            BOOL hasGroup = NO;
            ALAssetsGroup* targetAssetsGroup = nil;
            for (ALAssetsGroup* assetsGroup in groupArray) {
                
                NSString* name = [assetsGroup valueForProperty: ALAssetsGroupPropertyName];
                
                if ([name isEqualToString: blockGroupName]) {
                    hasGroup = YES;
                    targetAssetsGroup = assetsGroup;
                    break;
                }
            }
            
            if (!hasGroup) {
                [blockLibiary addAssetsGroupAlbumWithName: blockGroupName resultBlock:^(ALAssetsGroup *group) {
                    
                    [blockSelf saveImageToAssetsLibraryWithImageData: image andWithGroup: group];
                    
                } failureBlock:^(NSError *error) {
                    [blockSelf saveImageCallBack: nil];
                }];
            }
            else {
                [blockSelf saveImageToAssetsLibraryWithImageData: image andWithGroup: targetAssetsGroup];
            }
        }
    };
    
    [_assetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: listResultsBlock failureBlock:^(NSError *error) {
        [blockSelf saveImageCallBack: nil];
    }];
}

- (void)saveImageToAssetsLibraryWithImageData:(UIImage*)image andWithGroup:(ALAssetsGroup*)group{
    
    if (image == nil || group == nil) {
        [self saveImageCallBack: nil];
        return;
    }
    
    __block typeof(self) blockSelf = self;
    __weak typeof(_assetsLibrary) weakAssetsLibrary = _assetsLibrary;
    [_assetsLibrary writeImageToSavedPhotosAlbum: image.CGImage metadata: nil completionBlock:^(NSURL *assetURL, NSError *error) {
        [weakAssetsLibrary assetForURL: assetURL resultBlock:^(ALAsset *asset) {
            
            if ([group addAsset: asset]) {
                [blockSelf saveImageCallBack: asset];
            }
            
        } failureBlock:^(NSError *error) {
            [blockSelf saveImageCallBack: nil];
        }];
    }];
}

- (void)saveImageCallBack:(ALAsset*)asset {
    
    if (asset) {
        
//        NSURL* itemURL = [asset valueForProperty: ALAssetPropertyAssetURL];
        
        if (_delegate && [_delegate respondsToSelector: @selector(imagePickerController:didSelectedPhotos:)]) {
            [_delegate imagePickerController: self didSelectedPhotos: @[asset]];
        }
    }
    [[KKLoadingView sharedInstance] stopLoading];
    [_cameraPickerController dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [[KKLoadingView sharedInstance] loadingViewShowTips: @"保存中..." andWithEnable: true];
    UIImage* image = info[UIImagePickerControllerOriginalImage];
    [self saveImageToAssetsLibraryWithImage: image];
}

@end
